/* Author: Keir Kettle

*/
var edit; 
$(function() {
	
	if ($("input#encoded_html").length > 0)
	{
		putTextArea();
	}
	else
	{
		//we are on the home page - so fire the htmlarea() (if not wait for the click on the link)
		edit = $("#page").htmlarea();
	}
  	$.ajax({
	   type: "GET",
	   url: "/ajax/titles",
	   success: function(result){
			if (result.length > 0)
			{
				var treats = $.parseJSON(result); 
				var ul = $("<ul />");	
				var key = $("input#treat_key").val(); 				
				for (i in treats)
				{
					var title = treats[i].title; 
					if (title == "none")
					 {
						title = "untitled";
					 }
					 var li = $("<li />"); 
					 if (key == treats[i].key)
					 {
						li.text(title).css("font-weight", "bold"); 
					 }
					 else
					 {
						$("<a />").attr("href", "/page/" + treats[i].key).text(title).appendTo(li);
					 }
					 li.appendTo(ul);
				}
				$("div.treats").append(ul);
			}
			else
			{
				$("div.treats").append("<p>No saved pages</p>");
			}
			$("img.ajax", "div.treats").addClass("hidden");
			
	   }
	});	
	$("a#edit-page").bind("click", function(e) {
		e.preventDefault(); 
		$("div#display").hide(); 
		$("div#edit").show();
		edit = $("#page").htmlarea();
	});
	$("input#save").bind("click", function(e) {
		e.preventDefault(); 
		$(this).next("img.ajax").show(); 
		var method = ($("form").attr("id") == "new" ? "save" : "update");
		var title = $("#title").val();
		var page = getTextArea(); 
		var sendData =  "page=" + page + "&title=" + title; 
		if (method == "update")
		{
			sendData += "&treat_key=" + $("input#treat_key").val()
		}
		$.ajax({
			type: "POST",
			url: "/ajax/" + method, 
			data: sendData, 
			success: function(result, method){
				if (result.length > 0)
				{
					if (result == "OK")
					{
						
						$("p.save_message").show().fadeOut(1500, function() {});
					}
					else
					{
						var li = $("<li />"); 
						var link = $("<a />").attr("href", "page/" + result).text(title); 
						link.appendTo(li);
						$("div.treats ul").append(li);
						li.effect("highlight", {}, 3000);
						$("form")[0].reset();
						clearTextArea();
						$("input#save").next("img.ajax").hide();
					}
				}
			}
		});
		; 
		
	});
});
function clearTextArea() {
	var i = $("div.jHtmlArea div").eq(1).children("iframe").contents(); 
	$("body", i).html(""); 	
};
function getTextArea() {
	var i = $("div.jHtmlArea div").eq(1).children("iframe").contents(); 
	var html = $("body", i).html().replace(/"/g,"&quot;").replace(/'/g, "&apos;"); 	
	html = escape(html);
	// encode "/, ?, =, &, @, "
	html = html.replace(/\//g,"%2F").replace(/\?/g,"%3F").replace(/=/g,"%3D").replace(/&/g,"%26").replace(/@/g,"%40");
	return html;
};
function putTextArea() { 
	$("textarea#page").html(unescape($("input#encoded_html").val().replace("&apos;", "'").replace("&quot;", "\"")));
};
